import os.path
from flask import Flask, request, jsonify
from boss import BossZhiPinParser
import threading
import re
import tld

default_port = 5000

class Parser:
    def __init__(self, json, file_path:str=''):
        self._url = json['url']
        self._html = json['html']
        self.domain = tld.get_tld(self._url, as_object=True, fix_protocol=True).fld
        self.result = ''
        # print(self.domain, self._url)

        self.parser_list = [['zhipin.com', BossZhiPinParser]]
        for parser in self.parser_list:
            if self.domain == parser[0]:
                obj = parser[1](self._html)
                self.result = obj.put_info()
                self.write_file(file_path)
                break

    def put_info(self):
        return self.result

    def write_file(self, file_path:str):
        if not os.path.exists(file_path) or len(self.result):
            return

        print(self.result, '\n')

def init(name:str):
    _app = Flask(name)

    @_app.route('/parse', methods=['POST'])
    def _parse_html():
        data = request.get_json()
        parser = Parser(data)

        return jsonify({'result': 'success'})

    def _start():
        _app.run(port=default_port)

    t = threading.Thread(target=_start)
    t.start()

if __name__ == '__main__':
    init(__name__)